package com.acme.bankapp.service.bank;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.acme.bankapp.domain.bank.*;
import com.acme.bankapp.exceptions.ClientExistsException;

public class BankService {
	static final String MES_NULL_BANK_VARIABLE = "Object reference do not set to an instance of Bank object";
	static final String MES_NULL_CLIENT_VARIABLE = "Object reference do not set to an instance of Client object";
	
	static String BANK_SER_FILE = "bank.ser";

	public static void addClient(Bank bank, Client client) throws IllegalArgumentException, ClientExistsException {
		if (bank == null)
			throw new IllegalArgumentException(MES_NULL_BANK_VARIABLE);
		if (client == null)
			throw new IllegalArgumentException(MES_NULL_CLIENT_VARIABLE);
		
		bank.addClient(client);	
		
		try {
			saveBank(bank);
		} catch (IOException e) {
			System.out.println("Error while saving bank: "+ e.getMessage());
		}
	}
	
	public static void printMaximumAmountToWithdraw(Bank bank) throws IllegalArgumentException {
		if (bank == null)
			throw new IllegalArgumentException(MES_NULL_BANK_VARIABLE);
		
		System.out.println("Bank maximum amount to withdraw:");
		for (Client client : bank.getClients()) {
			System.out.print(String.format("Client <%s>: ", client.toString()));
			for (Account account : client.getAccounts()) {
				System.out.println(String.format("Max amount for account: %f", account.maximumAmountToWithdraw()));
			}
		}
		
	}

	public static void saveBank(Bank bank) throws FileNotFoundException, IOException {
		ObjectOutputStream stream = null;
		try {
			stream = new ObjectOutputStream(new FileOutputStream(BANK_SER_FILE));
			stream.writeObject(bank);
		} finally {
			if (stream != null)
				stream.close();
		}
	}
	
	public static Bank readBank(String filename) throws FileNotFoundException, IOException, ClassNotFoundException {
		ObjectInputStream stream = null;
		try {
			stream = new ObjectInputStream(new FileInputStream(filename));
			Bank bank = (Bank)stream.readObject();
			BANK_SER_FILE = filename;
			
			return bank;
		} finally {
			if (stream != null)
				stream.close();
		}
	}
}
